<template>
    <div class="login-wrap">
        <!-- <div class="logo-box">
            <img :src="loginData.logoImageUrl+''+loginData.loginImageFile" />
        </div> -->
        <div class="login-box-title">
            {{loginData.loginTitleMessage}}
        </div>
        <div class="login-box">
            <!-- <div class="box-title">{{ loginData.loginTitleMessage }}</div> -->
            <div class="box-content">
                <!-- <div class="login-title">
                    <img src="./../../assets/images/tou.png" />
                    <p>请登录</p>
                </div> -->
                <div class="content-title-logo" v-if="loginData.loginImageFile != ''">
                    <img :src="loginData.logoImageUrl+''+loginData.loginImageFile" />
                </div>
                <el-form :model="ruleForm" status-icon ref="ruleForm" class="login-form">
                    <el-form-item class="item-input">
                        <el-input v-model="ruleForm.username" placeholder="请输入登录用户名" auto-complete="off" @keyup.enter.native="submitForm('ruleForm')" />
                        <img class="item-icon" src="./../../assets/images/login_ren.png" />
                    </el-form-item>
                    <el-form-item class="item-input">
                        <el-input type="password" v-model="ruleForm.pass" placeholder="请输入登录密码" auto-complete="new-password" @keyup.enter.native="submitForm('ruleForm')" />
                        <img class="item-icon" src="./../../assets/images/login_suo.png" />
                    </el-form-item>
                    <el-form-item class="item-input">
                        <el-input v-model="ruleForm.verCode" placeholder="请输入验证码" auto-complete="off" style="width:60%;" @keyup.enter.native="submitForm('ruleForm')" />
                        <img class="item-icon" src="./../../assets/images/login_reg.png" />
                        <img style="width: 35%; height: 40px; float: right; border: solid 1px #ddd;box-sizing: border-box;" :src="captcha" @click="verCodeFn" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="width:100%;" :loading="loading" @click="submitForm('ruleForm')">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <el-dialog :close-on-click-modal="false" class="dialog-show"  :visible.sync="dialogVisibleShow" width='495px' @close="closeDialogVisible"  >
            <div class='ys-dialog-phone'>
                <span class="ys-phoneinfo">我们将发送短信验证码到您下面的手机号上</span>
                <p class="ys-phones">{{tellphones}}</p>
                <!-- {{timeDown2}}-9 {{flagCode}}--21  {{ErrorCode}}--2  -->
                <div class="ys-login-Code">
                    <input type="text" v-model="VerificationCode" maxlength="6"  placeholder="请输入短信验证码" />
                    <button v-if="flagCode && !ErrorCode" class="ys-timeDown">重新发送&nbsp;{{timeDown}}</button>
                    <button v-if="!flagCode && !ErrorCode" class="ys-GetCode" @click='GetCode' >{{getin?'获取验证码' : '重新获取'}}</button>
                    <button v-if="ErrorCode" class="ys-GetCode" style="color:#c6c6c6">{{getin?'获取验证码' : '重新获取'}}</button>
                </div>
                <p v-html="errorInfo" class="ys-errorInfo"></p>
                <div class="ys-submit" @click="Phonelogin">确定</div>
            </div>
        </el-dialog>
        <div class="login-footer">
            <p>版权所有:{{ loginData.loginCopyrightMessage }}&nbsp;&nbsp;&nbsp;&nbsp;联系电话:{{ loginData.loginTelphoneNumber }}</p>
            <p>地址:{{ loginData.loginAddressMessage }}</p>
        </div>
        <div class="login-version">
            {{ loginData.loginVersionMessage }}
        </div>
    </div>
</template>

<script>
import {
  mapState
} from 'vuex'
import API from '../../api/api_user'
export default {
    data() {
        // var validateUser = (rule, value, callback) => {
        //     this.$http.post('/ExperimentExtrance/system/mana/getLogIdExistMark',{
        //       'logId': this.ruleForm.username
        //     }).then((response) => {
        //       let res = response.data
        //       if(res.code !== 200){
        //         callback(new Error('请输入正确的登录用户名'))
        //       }else{
        //         callback()
        //       }
        //     },(err) => {
        //       console.log('err')
        //     })
        // }
        // var validatePass = (rule, value, callback) => {
        //     this.$http.post('/ExperimentExtrance/system/mana/getLogMsgExistMark', {
        //       'logId': this.ruleForm.username,
        //       'pwd': this.ruleForm.pass
        //     }).then((response) => {
        //       let res = response.data
        //       if(res.code !== 200){
        //         callback(new Error('请输入正确的登录密码'))
        //       }else{
        //         callback()
        //       }
        //     },(err) => {
        //       console.log('err')
        //     })
        // }
        return {
            loading: false,
            // urlType: null,
            loginData: '',
            ruleForm: {
                username: '',
                pass: '',
                verCode: ''
            },
            captcha: '',

            //yx 验证码功能
            //弹窗
            dialogVisibleShow:false,
            //验证码
            VerificationCode:'',
            //验证码标识
            flagCode:false,
            //倒计时初始值
            timeDown:60,
            getin:true,
            //定时器
            timer:'',
            //电话号码
            tellphones:'',
            //短信错误信息
            errorInfo:'',
            //获取信息或 重新发送置灰
            ErrorCode:false,
            //5分倒计时
            timeDown2:300,
            timer2:'',
        }
    },
    //实例创建完成后执行
    created(){
        // function getQueryString(name) {
        //     var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        //     var r = window.location.search.substr(1).match(reg);
        //     if (r != null) return unescape(r[2]);
        //     return null;
        // }
        // this.urlType = getQueryString('type')
        this.captcha  = '/dataplatform/system/mana/all/getVerificationCode?time=' + (new Date()).valueOf()

        this.init()     //初始化
        localStorage.removeItem('access-user');
        this.$store.commit('updateItemServiceValue', '')
        this.$store.commit('updateChapterType', '')
        this.$store.commit('updateItemServiceType', '')
        this.$nextTick(function () {
            if(window.screen.width < 1366){
                $('.login-wrap .login-box-title').css('margin', '2% auto 0')
                $('.login-wrap .login-box').css('margin', '0 auto')
            }
        })

    },
    computed: {
        ...mapState(['itemServiceValue', 'chapterType','itemServiceType', 'username'])
    },
    methods: {
        init(){
            let self = this
            self.$http.post('/dataplatform/getProjectLoginDisplayMessage').then(response => {
                let res = response.data
                if(res.code == '200'){
                    self.loginData = res.data
                    // localStorage.setItem('loginData', JSON.stringify(self.loginData));
                }
            })
        },
        //切换验证码
        verCodeFn(){
            this.captcha = '/dataplatform/system/mana/all/getVerificationCode?time=' + (new Date()).valueOf()
        },
        //登录
        submitForm (formName) {
            let self = this
            self.$refs[formName].validate((valid) => {
                if (valid) {
                    self.loading = true
                    let formData = new FormData();
                    formData.append('username', self.ruleForm.username);
                    formData.append('password', self.ruleForm.pass);
                    self.$http.post('/dataplatform/login?code='+self.ruleForm.verCode+'', formData, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then((response) => {
                        let res = response.data
                        if(res.code == '200'){
                            self.loading = false
                            self.$notify({
                                title : '提示信息',
                                message : '登录成功',
                                type : 'success'
                            })
                            let result = {}
                            if (res.data.systemDisplayMessageVO.loginImageFile == '') {
                                result = {
                                    id: res.data.id,
                                    userNumber: res.data.userNumber,
                                    username: res.data.userName,
                                    userSex: res.data.userSex,
                                    telephone: res.data.telephone,
                                    roleId: res.data.roleId,
                                    loginTitleMessage: res.data.systemDisplayMessageVO.loginTitleMessage,
                                    loginLogo: '',
                                    projectAccessUrl: res.data.systemDisplayMessageVO.projectAccessUrl,
                                    downloadAble: res.data.downloadAble
                                };
                            }else{
                                result = {
                                    id: res.data.id,
                                    userNumber: res.data.userNumber,
                                    username: res.data.userName,
                                    userSex: res.data.userSex,
                                    telephone: res.data.telephone,
                                    roleId: res.data.roleId,
                                    loginTitleMessage: res.data.systemDisplayMessageVO.loginTitleMessage,
                                    loginLogo: res.data.systemDisplayMessageVO.logoImageUrl+''+res.data.systemDisplayMessageVO.loginImageFile,
                                    projectAccessUrl: res.data.systemDisplayMessageVO.projectAccessUrl,
                                    downloadAble: res.data.downloadAble
                                };
                            }
                            localStorage.setItem('access-user', JSON.stringify(result))
                            // localStorage.setItem('username', JSON.stringify(res.data.userName))
                            // self.setcookie('access-user',JSON.stringify(result),6)
                            this.$store.commit('updateUserName', res.data.userName)
                            // 同时跳转到首页，这里使用vue-router实现
                            // 判断 roleId=1学生2教师3超级管理员
                            if(res.data.roleId == 1){
                                self.$router.replace({
                                    path:'/student/index'
                                })
                            }else if(res.data.roleId == 2){
                                self.$router.replace({
                                    path:'/teacher/index'
                                })
                            }else if(res.data.roleId == 3 || res.data.roleId == 4){
                                 self.$router.replace({
                                    path:'/admin/teacherMgt'
                                })
                            }
                        }
                        else if(res.code == 100107){
                            self.dialogVisibleShow = true
                            self.tellphones = res.data
                            self.loading = false
                        }
                        else {
                            self.captcha = '/dataplatform/system/mana/all/getVerificationCode?time=' + (new Date()).valueOf()
                            // 登录失败提示
                            self.$notify({
                                title : '提示信息',
                                message : res.message,
                                type : 'error'
                            })
                            self.loading = false
                        }
                    })
                }
            })
        },
         //关闭弹窗
        closeDialogVisible(){
            clearInterval(this.timer)
            clearInterval(this.timer2)
            this.timeDown = 60
            this.timeDown2 = 300
            this.VerificationCode = ''
            this.flagCode = false
            this.ErrorCode = false
            this.errorInfo = ''
        },
        // setcookie(name,value,daysToLive){
        //     var cookie = name + '=' + encodeURIComponent(value)
        //     if(typeof daysToLive == 'number'){
        //         cookie += ';max-age='+(daysToLive*60*60*24);
        //     }
        //     document.cookie = cookie;
        // }



        //yx
        //演示平台新增获取验证码
        GetCode(){
            let self = this
            clearInterval(self.timer)
            clearInterval(self.timer2)
            this.flagCode = true
            self.$http.post('/dataplatform/unauthorized/sms-code/send').then((response) => {
            //self.$http.post('/tes/unauthorized/sms-code/send-error').then((response) => {
                let res = response.data
                if(res.code == '200') {
                    self.Down()
                    // self.timer = setInterval(()=>{
                    //     self.flagCode = true
                    //     if(self.timeDown <= 1){
                    //         self.timeDown = 60
                    //         self.flagCode = false
                    //         self.getin = false
                    //         clearInterval(self.timer)
                    //     }
                    //     self.timeDown --

                    //  },1000)
                    self.VerificationCode = res.data
                    self.errorInfo = ''
                }else{
                    self.errorInfo = res.message
                    self.ErrorCode = true
                    self.Down2()
                    // self.timer2 = setInterval(()=>{
                    //     if(self.timeDown2 <= 1){
                    //         clearInterval(self.timer2)
                    //         self.timeDown2 = 5
                    //         self.flagCode = false
                    //         self.ErrorCode = false
                    //         self.getin = false
                    //     }
                    //     self.timeDown2 --

                    // },1000)
                }
            })
        },
        //倒计时
        Down(){
            let self = this
            self.timer = setInterval(()=>{
                self.flagCode = true
                if(self.timeDown <= 1){
                    self.timeDown = 60
                    self.flagCode = false
                    self.getin = false
                    clearInterval(self.timer)
                }
                self.timeDown --

            },1000)
        },
        Down2(){
            let self = this
            self.timer2 = setInterval(()=>{
                if(self.timeDown2 <= 1){
                    clearInterval(self.timer2)
                    self.timeDown2 = 300
                    self.flagCode = false
                    self.ErrorCode = false
                    self.getin = false
                }
                self.timeDown2 --

            },1000)
        },
        //短信登陆
        Phonelogin(){
            let self = this
            let reg = /^[0-9]+$/
            if(this.VerificationCode == ''){
                this.errorInfo = '请输入短信验证码'
                return
            }else if(!reg.test(this.VerificationCode)){
                this.errorInfo = '请输入6位数字验证码'
                return
            }

            let formData = new FormData();
                formData.append('username', self.ruleForm.username);
                formData.append('password', self.ruleForm.pass);
                formData.append('mobileCode', self.VerificationCode)

            self.$http.post('/dataplatform/login?code='+self.ruleForm.verCode+'', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                let res = response.data
                if (res.code == 200) {
                    //错误提示
                    self.errorInfo = ''
                    self.$notify({
                            title : '提示信息',
                            message : '登录成功',
                            type : 'success'
                        })
                        let result = {
                            id: res.data.id,
                            userNumber: res.data.userNumber,
                            username: res.data.userName,
                            userSex: res.data.userSex,
                            telephone: res.data.telephone,
                            roleId: res.data.roleId,
                            loginTitleMessage: res.data.systemDisplayMessageVO.loginTitleMessage,
                            loginLogo: res.data.systemDisplayMessageVO.logoImageUrl+''+res.data.systemDisplayMessageVO.loginImageFile,
                            projectAccessUrl: res.data.systemDisplayMessageVO.projectAccessUrl
                        };
                        localStorage.setItem('access-user', JSON.stringify(result))
                        // localStorage.setItem('username', JSON.stringify(res.data.userName))
                        // self.setcookie('access-user',JSON.stringify(result),6)
                        this.$store.commit('updateUserName', res.data.userName)
                        // 同时跳转到首页，这里使用vue-router实现
                        // 判断 roleId=1学生2教师3超级管理员
                        if(res.data.roleId == 1){
                            self.$router.replace({
                                path:'/student/index'
                            })
                        }else if(res.data.roleId == 2){
                            self.$router.replace({
                                path:'/teacher/index'
                            })
                        }else if(res.data.roleId == 3 || res.data.roleId == 4){
                                self.$router.replace({
                                path:'/admin/teacherMgt'
                            })
                        }

                }else if(res.code == 100107){
                    self.tellphones = res.data
                    self.errorInfo = res.message
                }
                else{
                    //错误提示
                    self.errorInfo = res.message
                }
            }).catch(err => {
                console(err)
            })
        }
    }
}
</script>

<style lang="scss">
    @import '@/assets/styles/login.scss';
</style>

<style lang="scss" scoped>
.login-wrap {
    background: url('../../assets/images/icon/bg.jpg') no-repeat;
    background-position: center;
}
</style>
